package com.community.service.impl;

import com.community.annotation.SysLog;
import com.community.base.BaseService;
import com.community.common.Const;
import com.community.common.ServerResponse;
import com.community.pojo.Answer;
import com.community.pojo.AnswerOperation;
import com.community.service.IAnswerOperationService;
import com.community.util.LoginUtil;
import com.community.util.NumberUtil;
import com.community.util.ToolUtil;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;

/**
 * 回答操作服务层
 */
@Service("iAnswerOperationService")
public class AnswerOperationServiceImpl extends BaseService implements IAnswerOperationService {

    /**
     * 操作回答
     * @param aid
     * @param type
     * @param userName
     * @return
     */
    @SysLog("操作回答")
    public ServerResponse<String> operation(int aid, int type, String userName, HttpServletRequest request){
        if(!LoginUtil.isLogin(request,userName)){//登录用户与参数用户不一致
            return ServerResponse.createByErrorMessage(Const.Msg.PARAMTERERROR);
        }
        //查询用户是否已经进行对应操作(生效状态的)
        int coutNum = answerOperationMapper.findByParam(aid,type,userName,Const.YesOrNo.YES);
        if(coutNum > 0){
            if(type == Const.AnswerOpertion.AGREE || type == Const.AnswerOpertion.OPPOSE ){
                //如果类型是赞同或者反对，则取消其赞同或者反对(设置对应为失效状态)
                answerOperationMapper.updatefForce(aid,type,userName,Const.YesOrNo.YES,Const.YesOrNo.NO);
                if(type == Const.AnswerOpertion.AGREE){
                    //更新回答点赞数
                    Answer answer = answerMapper.selectByPrimaryKey(aid);
                    if(NumberUtil.safeToNumber(answer.getLikeNums()) > 0){
                        int likeNums = answer.getLikeNums() - 1;
                        answer.setLikeNums(likeNums);
                        answerMapper.updateByPrimaryKeySelective(answer);
                    }
                }
                return ServerResponse.createBySuccessMessage(Const.Msg.SAVESUCCESS);
            }
        }
        //进行新增操作
        AnswerOperation answerOperation = new AnswerOperation();
        answerOperation.setAid(aid);//回答ID
        answerOperation.setType(type);//操作类型
        answerOperation.setUsername(userName);
        answerOperation.setIp(ToolUtil.getClientIp(request));//ip
        answerOperation.setForce(Const.YesOrNo.YES);//生效状态
        if(answerOperationMapper.insert(answerOperation) > 0){
            answerMapper.plusAnswerLikeNums(aid);//更新点赞数
            return ServerResponse.createBySuccessMessage(Const.Msg.SAVESUCCESS);
        }
        return ServerResponse.createByErrorMessage(Const.Msg.SAVEERROR);
    }

    /**
     * 根据回答查询点赞数(生效状态)
     * @param aid
     * @return
     */
    @SysLog("查询回答点赞数")
    public ServerResponse<Integer> countNumByAid(int aid,int force){
        return ServerResponse.createBySuccess(Const.Msg.SELECTSUCCESS,answerOperationMapper.countNumByAid(aid,force));
    }

}
